package cbm.commons;

import java.io.IOException;
import java.util.ResourceBundle;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SeguridadFilter implements Filter {
	
	private static ResourceBundle rb = ResourceBundle.getBundle("continuidadweb");

	public FilterConfig config;

    public SeguridadFilter() {
        
    }

	public void destroy() {
		
	} 

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		System.out.println("----------------------FILTRO SEGURIDAD---------------");
		try{
			HttpServletRequest req = (HttpServletRequest)request;
			//HttpServletResponse resp = (HttpServletResponse)response;
			HttpSession session = req.getSession();
			String uri = req.getRequestURI();
			String login = rb.getString("login");
			String pagLogin = rb.getString("pagina_login");
			SessionContainer sc = null;
			
			if(!uri.endsWith(login)){
				//Se valida si el usuario esta creado en la session
				sc = (SessionContainer)session.getAttribute(ConstantsWeb.SESSION_CONTAINER);
				if(sc == null){
					req.getRequestDispatcher(pagLogin).forward(request,response);
				}else{
					if(sc.getSessionElement(ConstantsWeb.USUARIO)== null){
						req.getRequestDispatcher(pagLogin).forward(request,response);
					}else{
						chain.doFilter(request, response);
					}
				}
			}else{
				chain.doFilter(request, response);
			}
		}catch(IOException e){
			e.printStackTrace();
			throw e;
		}catch(ServletException e){
			e.printStackTrace();
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

	public void init(FilterConfig fConfig) throws ServletException {
		this.config = fConfig;
	}
}
